﻿using log4net.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MSH.LogClient
{
    internal static class LoggingEventManage
    {
        /// <summary>
        /// 将Log4net实体转化为DTO实体
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static LogRequest ToLogRequest(this LoggingEvent item)
        {
            if (item == null) return null;
            try
            {
                var appId = item.Properties["AppId"].ToString();
                var defaultBusinessPosition = item.Properties["DefaultBusinessPosition"];

                var logData = item.MessageObject as LogData;

                var logRequest = new LogRequest()
                {
                    AppId = appId.ToString(),
                    BusinessPosition = logData.BusinessPosition ?? $"{defaultBusinessPosition}",
                    Content = logData.Message,
                    CreatTime = item.TimeStamp,
                    TraceInfo = logData.TraceInfo,
                    RequestId = logData.RequestId,
                };

                return logRequest;
            }
            catch
            {
                return null;
            }
        }

        public static LiteDbData<LogRequest> ToLiteDbData(this LoggingEvent item, string configName)
        {
            var req = item.ToLogRequest();
            var level = (int)MapLogLevel(item.Level);
            return new LiteDbData<LogRequest>(req, level, configName);
        }

        /// <summary>
        /// 保存日志信息
        /// </summary>
        /// <param name="item"></param>
        public static void Save(this LoggingEvent item, string configName)
        {
            var data = item.ToLogRequest();
            if (data == null) return;
            var level = (int)MapLogLevel(item.Level);
            LiteDBHelper.Save(data, level, configName);
        }

        /// <summary>
        /// 获取最老的LiteDbData
        /// </summary>
        /// <returns></returns>
        public static LiteDbData<LogRequest> GetLogRequest(string configName)
        {
            var data = LiteDBHelper.Get<LogRequest>(configName);
            if (data == null || data.Obj == null)
                return null;
            if (data != null && data.Obj == null)
            {
                LiteDBHelper.Remove<LogRequest>(data.Id);
                return null;
            }
            return data;
        }

        private static LogLevel MapLogLevel(Level level)
        {
            if (level == Level.Info) return LogLevel.Info;
            if (level == Level.Warn) return LogLevel.Warn;
            if (level == Level.Debug) return LogLevel.Debug;
            if (level == Level.Error) return LogLevel.Error;
            return LogLevel.Info;
        }
    }
}
